package com.ljy.system.marvel_sys.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ljy.system.marvel_sys.system.model.role.Role;
import com.ljy.system.marvel_sys.system.model.user.User;
import com.ljy.system.marvel_sys.system.model.user.UserRole;
import com.ljy.system.marvel_sys.system.service.IRoleService;
import com.ljy.system.marvel_sys.system.service.IUserRoleService;
import com.ljy.system.marvel_sys.system.service.IUserService;
import com.ljy.system.marvel_sys.common.util.QiniuCloundUtil;
import com.ljy.system.marvel_sys.common.util.md5.Md5Util;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 用户管理相关
 * @author LiJunYi
 * @create 2019/7/3
 * @since 1.0.0
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    IUserService userService;
    @Autowired
    IRoleService roleService;
    @Autowired
    IUserRoleService userRoleService;

    @RequestMapping("list")
    @RequiresPermissions(value = "user:list")
    @ResponseBody
    public Map<String,Object> queryUsers(String userName,String departmentName,int limit,int page){
        IPage<User> users = userService.queryUser(userName,departmentName,limit,page);
        Map<String,Object> resultMap = new HashMap<>(200);
        resultMap.put("code",0);
        resultMap.put("msg","");
        resultMap.put("data",users.getRecords());
        resultMap.put("count",users.getTotal());
        return resultMap;
    }

    /**查看用户角色*/
    @RequestMapping("role/{userId}")
    public String userRole(@PathVariable("userId") int userId, Model model){
        // 1、获取该用户角色
        List<UserRole> userRoles = userRoleService.listUserRoles(userId);
        List<Long> roleIds = new ArrayList<>();
        for (UserRole userRole:userRoles ){
            roleIds.add(userRole.getRoleId());
        }
        // 角色表数据
        List<Role> roles = roleService.listRoles();
        // 未分配角色
        List<Role> unassignRoles = new ArrayList<>();
        // 已分配角色
        List<Role> assingedRoles = new ArrayList<>();

        for (Role role : roles) {
            if (roleIds.contains(role.getId())) {
                assingedRoles.add(role);
            } else {
                unassignRoles.add(role);
            }
        }
        model.addAttribute("assingedRoles", assingedRoles);
        model.addAttribute("unassignRoles", unassignRoles);
        model.addAttribute("userId", userId);
        return "user/assign";
    }

    /**更新用户角色*/
    @RequiresRoles(value = "admin")
    @RequestMapping("assign")
    @ResponseBody
    public int assignRole(String roleId,String userId){
        long rId = Long.parseLong(roleId);
        long uId = Long.parseLong(userId);
        int i = userRoleService.upateUserRole(rId, uId);
        return i;
    }

    /**
     * 用户修改密码
     * 1、根据用户名以及密码确认旧密码是否正确
     * */
    @RequestMapping("check")
    @ResponseBody
    public String checkPswByUserName(String userName,String oldPsw){
        User user = userService.queryByUserName(userName);
        String md5OldPsw = Md5Util.md5Password(oldPsw,userName);
        if(md5OldPsw.equals(user.getUserPassword())){
            String msg = user.getId()+"";
            return msg;
        }else {
            return "";
        }
    }
    /**
    * 2、更新用户密码
    * */
    @RequestMapping("update")
    @ResponseBody
    public String updateUserPsw(User user){
        String psw = user.getUserPassword();
        psw = Md5Util.md5Password(psw, user.getUserName());
        user.setUserPassword(psw);
        int i =  userService.updateUserPsw(user);
        if(i != 0){
            return "密码修改成功";
        }else{
            return "密码修改失败";
        }
    }

    /**用于查看个人信息*/
    @RequestMapping("info")
    public String userInfo(){
        return "user/info";
    }

    /**用户修改头像*/
    @RequestMapping("img/{userId}")
    @ResponseBody
    public Map<String ,Object> updateImg(@PathVariable("userId") int userId,@RequestParam("file")  MultipartFile file){
        Map<String,Object> map = new HashMap<>(200);
        try {
            FileInputStream inputStream = (FileInputStream) file.getInputStream();
            /*file.transferTo(file1);*/
            String filePath = QiniuCloundUtil.uploadImg(inputStream,null);
            map.put("code", 0);
            map.put("msg", "上传成功");
            map.put("src", filePath);
            /*更新用户头像*/
            User user = new User();
            user.setId(userId);
            user.setUserImg(filePath);
            userService.updateUserImg(user);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            map.put("code",500);
            map.put("msg", "上传失败");
            map.put("src", "");
            return map;
        }
    }

    /**个人用户信息*/
    @RequestMapping("renewal")
    @ResponseBody
    public String updateUser(User user){
        int i = userService.updateUser(user);
        if(i >0){
            return "更新成功";
        }else{
            return "更新失败";
        }
    }

    /** 更改用户状态*/
    @RequestMapping("update_user_type")
    @ResponseBody
    @RequiresRoles("admin")
    public String updateUserType(User user){
        int i = userService.updateUserType(user);
        if(i > 0){
            return "操作成功";
        }else{
            return "操作失败";
        }
    }

    /** 更改用户部门信息*/
    @RequestMapping("update_user_dep/{id}/{depId}")
    @ResponseBody
    public Map<String,Object> updateUserDep(@PathVariable("id") int id,@PathVariable("depId") int depId){
        long userId = id;
        long departmentId = depId;
        Map<String,Object> map = new HashMap<>(200);
        int i = userService.updateUserDep(userId, departmentId);
        if(i >0){
            map.put("msg", "ok");
        }else{
            map.put("msg", "error");
        }
        return map;
    }
}
